package net.dgg.zz.production.chargeback.service;

import com.alibaba.fastjson.JSONObject;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.OrfApiService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.http.ResultObj;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.datapermission.entity.DataAuthDTO;
import net.dgg.tmd.foundation.platform.datapermission.service.DataPermissionAssocService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserDTO;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.dao.SystemRecordDao;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.production.chargeback.dao.ZzAuditOrderDao;
import net.dgg.zz.production.chargeback.dao.ZzProductOrderDao;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.inProcess.dao.ProductNodeFlowDao;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import net.dgg.zz.production.vo.InprocessOrderVo;
import net.dgg.zz.production.vo.JunctionsOrderVo;
import net.dgg.zz.production.vo.OrgOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

@Service
public class ZzAuditOrderServic extends BaseService {

    @Autowired
    private ZzAuditOrderDao zzAuditOrderDao;
    @Autowired
    private ZzProductOrderDao zzProductOrderDao;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private ProductNodeFlowDao productNodeFlowDao;
    @Autowired
    private CommonMangerExtService zzCommonMangerExtService;
    @Autowired
    private DataPermissionAssocService dataPermissionAssocService;
    @Autowired
    private OrfApiService orfApiService;
    @Autowired
    private ZzInProcessService zzInProcessService;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private SystemRecordDao systemRecordDao;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonService commonService;

    /**
     * 查询分页列表
     *
     * @param map {codeName:模块名称}
     * @return List<ScProductOrder>
     */
    @Transactional(readOnly = true)
    public List<Map> queryAuditListPage(Map map) {
        //  zzsc_sc_audit
        DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds("zzsc_sc_junctions");
        map.put("dataAuthDTO", dataAuthDTO);
        map.put("userAlias", "t");
        map.put("userColumn", "flow_user_id");
        map.put("deptAlias", "t");
        map.put("deptColumn", "flow_user_org_id");
        Integer count = this.zzAuditOrderDao.count(map);
        map.put("count", count);
        if (count <= 0) {
            return new ArrayList<Map>(0);
        }
        if (null == map.get("orderColumn")) {
            map.put("orderDir", "desc");
            map.put("orderColumn", "t.create_time");
        }
        List<Map> listPage = zzAuditOrderDao.queryMap(map);
        map.put("count", count);
        return listPage;
    }


    /**
     * 审核界面data
     *
     * @param id
     * @return
     */
    public Map auditOrder(Long id) {
        Map map = new HashMap<>();
        UserEntity userEntity = sessionManager.getCurrentUser();
        Assert.notNull(userEntity, "未获取到登陆人，请重新登录！");
        Assert.notNull(id, "生产订单ID不能为空！");
        SystemRecord systemRecord = new SystemRecord();
        Map flowMap = new HashMap<>();
        ProductOrder productOrder = zzProductOrderDao.getById(id);
        Assert.notNull(productOrder, "未查询到此生产主订单，请刷新列表！");
        map.put("scProductOrder", productOrder);
        productOrder.setAbandonReason(translateUtil.translateCode(productOrder.getAbandonReason()));
        flowMap.put("workId", productOrder.getId());
        flowMap.put("operateType", "19"); //查询退单的
        systemRecord = systemRecordDao.getByParamsSystemRecord(flowMap);
        map.put("flowOperating", systemRecord);
        return map;
    }

    /**
     * 查询节点流程
     *
     * @param id
     * @return
     */
    public ProductNodeFlow queryNodeFlowById(Long id) {
        Assert.notNull(id, "节点流程id为空！");
        ProductNodeFlow scProductNodeFlow = productNodeFlowDao.queryFlowById(new HashMap() {{
            put("flowId", id);
        }});
        return scProductNodeFlow;
    }
    /**
     * 查询节点流程
     *
     * @param
     * @return
     */
    public String queryAuditLevel(String flowContent) {
        if(StringUtils.isEmpty(flowContent)){
            return "1";
        }
        JSONObject resultObj = JSONObject.parseObject(flowContent);
        if(!net.dgg.iboss.base.util.StringUtils.isEmptyObj(resultObj.getString("data"))){
            resultObj = (JSONObject) resultObj.get("data");
        }
        List<Map<String, Object>> nodeDtoList = (List) resultObj.get("nodeDtoList");
        if(nodeDtoList.size() < 0){
            return "1";
        }else{
            return "2";
        }

    }


    /**
     * 审核退单
     *
     * @param
     */
    @Transactional
    public void auditOrChargeBackOrder(String id, String type, String auditorId, String remark, UserEntity userEntity) {
        Assert.notNull(userEntity, "未获取到登陆人，请重新登录！");
        Assert.notNull(id, "生产订单ID不能为空！");
        ProductOrder scProductOrder = this.zzProductOrderDao.getById(Long.valueOf(id));
        Assert.isTrue(scProductOrder.getStatus().equals("ZZSC_STATE_SCPROORDER_CODE8"),"生产订单状态已改变，请刷新页面！");
        Assert.isTrue(scProductOrder.getAuditorId().equals(userEntity.getId()), "您不是当前审核人，没有权限操作！");
        Assert.notNull(scProductOrder, "未查询到此生产订单，请刷新列表！");
        Map auditorUser = new HashMap<>();
        SystemRecord systemRecord = new SystemRecord();
        StringBuilder ids = new StringBuilder();
        String result="";//审核结果
        if (!"".equals(remark)) {
            scProductOrder.setRemark(remark);
            scProductOrder.setLastRemark(remark);
        }
        if (!"".equals(auditorId) && null != auditorId) {
            auditorUser = zzCommonMangerExtService.searchUserById(Long.parseLong(auditorId));
        }
        //同意
        if (type.equals("1")) {
            //--------证明是最后一次审核-------------
            if ("".equals(auditorId) || null == auditorId) {
                result="已退单";
                scProductOrder.setReturnAbandonCompleteTime(new Date()); //退废单完成时间
                scProductOrder.setStatus(ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK); //已退单
                //同步修改子订单接口
                //zzInProcessService.updateOrderBusiness(scProductOrder, userEntity, "ORF_BDZT_2");
                //完结调用回访接口
                //zzInProcessService.saveRevisitCustomer(scProductOrder, userEntity, "BUS_STA_2_4");
                systemRecord.setOperateType("46");

                //审核通过后需要删除相关预约,取消相关证书和资质的预定,匹配,使用等
                zzInProcessService.updateAllCertificateQualification(Long.valueOf(id),userEntity);
            } else {
                systemRecord.setOperateType("46");//操作类型 : 审核通过
                scProductOrder.setAuditorId(Long.parseLong(auditorUser.get("id").toString())); //下一审核人id
                scProductOrder.setAuditorName(auditorUser.get("realName").toString() + auditorUser.get("loginName"));//审核名称
                //如果是第一次审核
                if (null == scProductOrder.getAbandonReasonNum()) {
                    scProductOrder.setAbandonReasonNum(1);
                } else { //第N次审核，审核次数n+1
                    scProductOrder.setAbandonReasonNum(scProductOrder.getAbandonReasonNum() + 1);//审核级数+1
                }
            }
        } else {//不同意
            result="退单驳回";
            scProductOrder.setStatus(ScProductConstant.SC_ORDER_CHARGEBACK_TDBH); //退单驳回
            systemRecord.setOperateType("47");//操作类型 : 审核驳回
            this.cmsService.sendMessage(scProductOrder.getFlowUserId(), userEntity.getId(),
                    new String[]{scProductOrder.getScProductOrderNo(), DateUtil.dateToString(scProductOrder.getUpdateTime())},
                    ScProductConstant.ZZSC_PRODUCT_ORDER_CHANGE_BACK_MSG, 2);

        }
        updateOpt(scProductOrder, userEntity);
        scProductOrder.setLastRemarkTime(new Date());
        zzProductOrderDao.update(scProductOrder);
        //-------操作记录------------
        systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
        systemRecord.setWorkId(scProductOrder.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setRemarks("退单审核(结果 " + ("1".equals(type) ? "同意" : "不同意") + "):" + remark);
        systemRecord.setSource("2");//来源生产
        systemRecordService.save(systemRecord);
        //-------调用公共的备注方法---------
//        if (null != remark && !"".equals(remark)) {
//            if (type.equals("1")) { //同意
//                zzInProcessService.syscScOrderRemarkToUc(scProductOrder, userEntity, ScProductConstant.SC_CZ_REFUSE_RETURN);
//            }
//        } else { //不同意
//            zzInProcessService.syscScOrderRemarkToUc(scProductOrder, userEntity, ScProductConstant.SC_CZ_REFUSE_RETURN);
//        }

        //判断生产子订单是否全部已退单，全部退单调同步订单状态接口
        Integer status = 1;
        List<ProductOrder> scProductOrderList = zzProductOrderDao.query(new HashMap() {{
            put("orderId", scProductOrder.getOrderId());
            put("orderStatus", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);
        }});
        if (scProductOrderList.size() > 0)

        {
            for (ProductOrder scProductOrder1 : scProductOrderList) {
                if (!scProductOrder1.getStatus().equals(ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK)) { //不是退单的
                    status++;
                }
            }
        }
        //证明全部已经退单
        if (status == 1) {
            //调同步接口
            orfApiService.updateOrder(scProductOrder.getOrderId(), userEntity.getId(), "ORF_DDZT_3", null);
        }
        try {
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProductOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(scProductOrder.getId());
            customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE7);
            customerRecord.setCreaterId(userEntity.getId());
            if (StringUtils.isNotEmpty(remark)){
                customerRecord.setContent(remark);
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  userEntity);

            String msgConent="您好，您的客户"+scProductOrder.getCustomerName()+"订单"+scProductOrder.getOrderNo()+"办理的"
                    +scProductOrder.getScProductOrderNo()+"业务,订单"+result+",请及时确认处理";
            commonService.sendQgjMessage(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
        }catch (Exception e){
            //不处理也不抛出,不成功就算了
        }
    }


    /**
     * 变更审核人
     *
     * @param
     */
    @Transactional
    public void updateAuditor(String id, String auditorId, String remark) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        Assert.notNull(userEntity, "未获取到登陆人，请重新登录！");
        Assert.notNull(id, "生产订单ID不能为空！");
        ProductOrder scProductOrder = this.zzProductOrderDao.getById(Long.valueOf(id));
        Assert.isTrue(scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_CHARGEBACK_DSH),"生产订单状态已改变，请刷新页面！");
        Assert.notNull(scProductOrder, "未查询到此生产订单，请刷新列表！");
        Map auditorUser = zzCommonMangerExtService.searchUserById(Long.parseLong(auditorId));
        Assert.notNull(auditorUser, "未获取到变更审核人的信息，请重新选择审核人！");
        SystemRecord systemRecord = new SystemRecord();
        if (StringUtils.isNotEmpty(remark)) {
            scProductOrder.setRemark(remark);
            systemRecord.setRemarks(remark);
            //最新备注时间
            scProductOrder.setLastRemarkTime(new Date());
            scProductOrder.setLastRemark(remark);
        }
        scProductOrder.setAuditorId(Long.parseLong(auditorUser.get("id").toString()));
        scProductOrder.setAuditorName(auditorUser.get("realName").toString().concat(auditorUser.get("loginName").toString()));
        this.updateOpt(scProductOrder, userEntity);
        zzProductOrderDao.update(scProductOrder);
        //-------操作记录------------
        systemRecord.setWorkId(scProductOrder.getId());
        systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setSource("2");//来源生产
        systemRecord.setOperateType("34");//操作类型 : 变更审核人
        systemRecordService.save(systemRecord);
       // -------调用公共的备注方法---------
//        if (null != remark && !"".equals(remark)) {
//            zzInProcessService.syscScOrderRemarkToUc(scProductOrder, userEntity, ScProductConstant.SC_CZ_WITHDRAWN_AUDITOR_TD);
//        }
        try {
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProductOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(scProductOrder.getId());
            customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE8);
            customerRecord.setCreaterId(userEntity.getId());
            if (StringUtils.isNotEmpty(remark)){
                customerRecord.setContent(remark);
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  userEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 撤回
     *
     * @param id 孙上峰
     */
    @Transactional
    public void toTithdrawOrder(Long id) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        Assert.notNull(userEntity, "未获取到登陆人，请重新登录！");
        Assert.notNull(id, "生产订单ID不能为空！");
        ProductOrder scProductOrder = this.zzProductOrderDao.getById(Long.valueOf(id));
        Assert.notNull(scProductOrder, "未查询到此生产订单，请刷新列表！");
        Assert.isTrue(scProductOrder.getAbandonUserId().equals(userEntity.getId()), "您没有权限，只能申请人才能操作撤回！");
        Assert.isTrue(scProductOrder.getStatus().equals("ZZSC_STATE_SCPROORDER_CODE8"),"生产订单已审核，无法撤回！");
        scProductOrder.setAbandonReasonNum(null); //审核级数设置为null
        scProductOrder.setStatus(scProductOrder.getBeforeStatus());//状态改为订单申请退废单前的状态
        this.updateOpt(scProductOrder, userEntity);
        //-------操作记录------------
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
        systemRecord.setWorkId(scProductOrder.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setRemarks("退单撤回");
        systemRecord.setSource("2");//来源生产
        systemRecord.setOperateType("35");//操作类型 : 撤回
        systemRecordService.save(systemRecord);
        zzProductOrderDao.update(scProductOrder);
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(scProductOrder.getCustomerId());
        customerRecord.setTableName("zzsc_product_order");
        customerRecord.setTableId(scProductOrder.getId());
        customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE21);
        customerRecord.setCreaterId(userEntity.getId());
        customerRecord.setContent("撤回订单");
        MQMessageSendUtil.ucMessageSend(customerRecord);

        //提交之后，将订单信息同步到企大顺生产中心
        MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  userEntity);
    }


    @Transactional(readOnly = true)
    public List<Map> teamAuditOrderListData(Map map) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        List<Long> orgIdList =zzCommonMangerExtService.getChildOrganizationList(userEntity.getOrgId());
        map.put("orgIdList", orgIdList);//获取本部门以及下属部门
        Map userMap = new HashMap(){{put("orgIds",orgIdList);put("locked",0);}};
        List<UserDTO> userDTOPage = userService.findUserDTOPage(userMap);//查部门下面所有人
        List<Long> userIds = new ArrayList<>();
        for (UserDTO userDTO : userDTOPage) {
            userIds.add(userDTO.getId());
        }
        map.put("userIds",userIds);
        Integer count = this.zzAuditOrderDao.count(map);
        map.put("count", count);
        if (count <= 0) {
            return new ArrayList<>(0);
        }
        List<Map> listPage = zzAuditOrderDao.queryMap(map);
        map.put("count", count);
        return listPage;
    }

    /**
     * <p>@Description 结项订单导出</p>
     * <p>@author zhangwen</p>
     * <p>@Time 2018/8/31 0031 16:21 创建时间</p>
     * <p>@return</p>
     */
    public List<JunctionsOrderVo> findExportProductOrder(Map params) {

        DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds("zzsc_sc_audit");
        params.put("dataAuthDTO", dataAuthDTO);
        params.put("userAlias", "t");
        params.put("userColumn", "flow_user_id");
        params.put("deptAlias", "t");
        params.put("deptColumn", "flow_user_org_id");
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");
            params.put("orderColumn", "createTime");
        }

        List<Map> srList = zzAuditOrderDao.queryMap(params);

        String[] transColum = {"originCode","status"};
        srList = translateUtil.translateList(transColum, srList);
        List<JunctionsOrderVo> voList = new LinkedList<>();
        for (Map map : srList) {
            JunctionsOrderVo vo = new JunctionsOrderVo();
            vo.setSignOrgName(String.valueOf(map.get("signOrgName") == null ? "" : map.get("signOrgName")));
            vo.setOrderNo(String.valueOf(map.get("orderNo") == null ? "" : map.get("orderNo")));
            vo.setScProductOrderNo(String.valueOf(map.get("scProductOrderNo") == null ? "" : map.get("scProductOrderNo")));
            vo.setCustomerName(String.valueOf(map.get("customerName") == null ? "" : map.get("customerName")));
            vo.setBusinessProductName(String.valueOf(map.get("businessProductName") == null ? "" : map.get("businessProductName")));
            vo.setProductName(String.valueOf(map.get("productName") == null ? "" : map.get("productName")));
            vo.setSignTime(String.valueOf(map.get("orderTime") == null ? "" : DateUtils.dateString((Date) map.get("orderTime"),"yyyy-MM-dd HH:mm:ss")));//签单时间
            vo.setSignUserName(String.valueOf(map.get("signUserName") == null ? "" : map.get("signUserName")));
            vo.setSignUserOrgName(String.valueOf(map.get("signUserOrgName") == null ? "" : map.get("signUserOrgName")));
            vo.setFlowUserName(String.valueOf(map.get("flowUserName") == null ? "" : map.get("flowUserName")));
            vo.setFlowUserOrgName(String.valueOf(map.get("flowUserOrgName") == null ? "" : map.get("flowUserOrgName")));
            vo.setCompanyName(String.valueOf(map.get("companyName") == null ? "" : map.get("companyName")));//企业名称
            vo.setContractNo(String.valueOf(map.get("contractNo") == null ? "" : map.get("contractNo")));//合同编号
            voList.add(vo);
        }
        return voList;
    }



}
